const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 路由
app.use('/api', require('./routes/api'));

// 下载模型（如果不存在）
const downloadModels = async () => {
  const modelsDir = path.join(__dirname, 'models');
    // 从本地加载模型
    console.log('从本地加载模型...');
    const faceapi = require('face-api.js');
    const { Canvas, Image } = require('canvas');
    faceapi.env.monkeyPatch({ Canvas, Image });
    
    try {
      await faceapi.nets.ssdMobilenetv1.loadFromDisk(modelsDir);
      await faceapi.nets.faceLandmark68Net.loadFromDisk(modelsDir);
      await faceapi.nets.faceRecognitionNet.loadFromDisk(modelsDir);
      console.log('模型加载完成');
    } catch (error) {
      console.error('模型加载失败:', error);
    }
};

// 启动服务器
app.listen(PORT, async () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  
  try {
    await downloadModels();
  } catch (error) {
    console.error('下载模型失败:', error);
    console.log('请手动下载模型到 ./models 目录');
  }
});